import { JavascriptGenerator, javascriptGenerator } from "blockly/javascript";
import { Tanslate } from "./translate";
import * as Blockly from 'blockly/core';
import { WorkspaceSvg } from "blockly/core";
import { getValue } from "./com";

export namespace Texts {
    const blocks = [
        {
            'key': 'text',
            'message0': '%1',
            'args0': [
                {
                    'type': 'field_input',
                    'name': 'TEXT',
                    'text': '',
                },
            ],
            'output': 'String',
            'style': 'text_blocks',
            'helpUrl': '%{BKY_TEXT_TEXT_HELPURL}',
            'tooltip': '%{BKY_TEXT_TEXT_TOOLTIP}',
        },
        {
            'key': 'text_append',
            'message0': '%1 + %2',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VAR',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'TEXT',
                    'check': 'String',
                },
            ],
            'output': 'String',
            "inputsInline": true,
            'style': 'text_blocks',
        },
        {
            'key': 'text_equals',
            'message0': '%1 = %2',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'A',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'B',
                    'check': 'String',
                },
            ],
            "inputsInline": true,
            'output': 'Boolean',
            'style': 'text_blocks',
        },
        {
            'key': 'text_length',
            'message0': '%{BKY_TEXT_LENGTH_TITLE}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
            ],
            'output': 'Number',
            'style': 'text_blocks',
            'tooltip': '%{BKY_TEXT_LENGTH_TOOLTIP}',
            'helpUrl': '%{BKY_TEXT_LENGTH_HELPURL}',
        },
        {
            'key': 'text_isEmpty',
            'message0': '%{BKY_TEXT_ISEMPTY_TITLE}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
            ],
            'output': 'Boolean',
            'style': 'text_blocks',
            'tooltip': '%{BKY_TEXT_ISEMPTY_TOOLTIP}',
            'helpUrl': '%{BKY_TEXT_ISEMPTY_HELPURL}',
        },
        {
            'key': 'text_indexOf',
            'message0': '%{BKY_TEXT_INDEXOF_TITLE}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'field_dropdown',
                    'name': 'END',
                    'options': [
                        ['%{BKY_TEXT_INDEXOF_OPERATOR_FIRST}', 'FIRST'],
                        ['%{BKY_TEXT_INDEXOF_OPERATOR_LAST}', 'LAST'],
                    ],
                },
                {
                    'type': 'input_value',
                    'name': 'FIND',
                    'check': 'String',
                },
            ],
            'output': 'Number',
            'style': 'text_blocks',
            'helpUrl': '%{BKY_TEXT_INDEXOF_HELPURL}',
            'inputsInline': true
        },
        {
            'key': 'text_charAt',
            'message0': '%{BKY_TEXT_CHARAT_TITLE}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'WHERE',
                    'check': 'Number',
                },
            ],
            'output': 'String',
            'style': 'text_blocks',
            'tooltip': '%{text_charAt_tips}',
            'inputsInline': true,
        },
        {
            'key': 'text_includes',
            'message0': '%1 %{text_includes} %2',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'WHERE',
                    'check': 'String',
                },
            ],
            'output': 'Boolean',
            'style': 'text_blocks',
            'inputsInline': true,
        },
        {
            'key': 'text_replace',
            'message0': '%{from} %1 %{text_replace_find} %2 %{text_replace} %3',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'WHERE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'VAR',
                    'check': 'String',
                },
            ],
            'output': 'String',
            'style': 'text_blocks',
            'inputsInline': true,
        },
        {
            'key': 'text_split',
            'message0': '%{use} %1 %{text_split} %2',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'WHERE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
            ],
            'output': 'Array',
            'style': 'text_blocks',
            'inputsInline': true,
        },
        {
            'key': 'text_substring',
            'message0': '%{text_substring} %1 %{from} %2 %{to} %3',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'START',
                    'check': 'Number',
                },
                {
                    'type': 'input_value',
                    'name': 'END',
                    'check': 'Number',
                },
            ],
            'output': 'String',
            'style': 'text_blocks',
            'inputsInline': true,
        },
        {
            'key': 'text_code_from',
            'message0': '%{from} %1 %{get} %{texts}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'Number',
                }
            ],
            'output': 'String',
            'style': 'text_blocks',
            'inputsInline': true,
            'tooltip': '%{text_code_from_tips}',
        },
        {
            'key': 'text_code_to',
            'message0': '%{from} %1 %{list_the} %2 %{list_th} %{to} %{text_ascii_code}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
                {
                    'type': 'input_value',
                    'name': 'INDEX',
                    'check': 'Number',
                }
            ],
            'output': 'Number',
            'style': 'text_blocks',
            'inputsInline': true,
            'tooltip': '%{text_code_to_tips}',
        },
        {
            "key": "text_encoder",
            "message0": "%{text_encoder}",
            "output": "text_encoder",
            "inputsInline": true,
            'style': 'text_blocks',
            'tooltip': '%{text_encoder_tips}',
        },
        {
            "key": "text_encoder_encode",
            "message0": "%1 %{text_encoder_encode} %2",
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'TARGET',
                    'check': 'text_encoder',
                },
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'String',
                },
            ],
            "output": "uint8Array",
            "inputsInline": true,
            'style': 'text_blocks',
            'tooltip': '%{text_encoder_tips}',
        },
        {
            "key": "text_decoder",
            "message0": "%{text_decoder}",
            "output": "text_decoder",
            "inputsInline": true,
            'style': 'text_blocks',
            'tooltip': '%{text_decoder_tips}',
        },
        {
            "key": "text_decoder_decode",
            "message0": "%1 %{text_decoder_decode} %2",
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'TARGET',
                    'check': 'text_decoder',
                },
                {
                    'type': 'input_value',
                    'name': 'VALUE',
                    'check': 'uint8Array',
                },
            ],
            "output": "String",
            "inputsInline": true,
            'style': 'text_blocks',
            'tooltip': '%{text_decoder_tips}',
        },
    ]
    export function init() {
        initGenerator()
        Tanslate.tr(blocks).forEach((item: any) => {
            Blockly.Blocks[item.key] = {
                init: function (this: Blockly.Block) {
                    this.jsonInit(item);
                    if (item.key === 'texts') {
                        this.setOnChange((e) => {
                            const ws = this.workspace as WorkspaceSvg;
                            if (
                                !ws.isDragging ||
                                ws.isDragging() ||
                                (e.type !== Blockly.Events.BLOCK_MOVE && e.type !== Blockly.Events.BLOCK_CREATE)
                            ) {
                                return;
                            }
                            if (needAdd(this)) {
                                //this.appendValueInput('value_' + this.getChildren(false).length);
                            }
                        })
                    }
                }
            }
        })
    }

    export function getTools() {
        const colorsBlocks = {
            kind: 'category',
            name: Blockly.Msg['texts'],
            'colour': 159,
            contents: [] as any[]
        }
        blocks.forEach((item: any) => {
            colorsBlocks.contents.push({
                kind: 'block',
                type: item.key
            })
        })

        return colorsBlocks
    }
    const addSate = {
        last: 0
    }
    function needAdd(block: Blockly.Block) {
        const now = Date.now()
        if (addSate.last > 0 && now < addSate.last) {
            return false
        }
        const xy = block.getRelativeToSurfaceXY()
        if (xy.x < 40) {
            return false
        }
        addSate.last = now + 1000
        const ar = block.getChildren(false)
        const size = block.inputList.length
        return ar.length + 1 === size
    }

    function initGenerator() {

        javascriptGenerator.forBlock['text_append'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VAR = getValue(block, generator, 'VAR')
            const TEXT = getValue(block, generator, 'TEXT')
            if (!VAR || !TEXT) {
                throw new Error(block.id)
            };
            return `${VAR} + ${TEXT}`;
        }

        javascriptGenerator.forBlock['text_equals'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const A = getValue(block, generator, 'A')
            const B = getValue(block, generator, 'B')
            if (!A || !B) {
                throw new Error(block.id)
            };
            return `${A} === ${B}`;
        }

        javascriptGenerator.forBlock['text_length'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            if (!VALUE) {
                throw new Error(block.id)
            };
            return `${VALUE}.length`;
        }

        javascriptGenerator.forBlock['text_isEmpty'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            if (!VALUE) {
                throw new Error(block.id)
            };
            return `String(${VALUE}||'').trim().length === 0`;
        }

        javascriptGenerator.forBlock['text_indexOf'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const FIND = getValue(block, generator, 'FIND')
            const END = getValue(block, generator, 'END')
            if (!VALUE || !FIND || !END) {
                throw new Error(block.id)
            };
            if (END === 'FIRST') {
                return `${VALUE}.indexOf(${FIND})`;
            } else {
                return `${VALUE}.lastIndexOf(${FIND})`;
            }
        }

        javascriptGenerator.forBlock['text_charAt'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const WHERE = getValue(block, generator, 'WHERE')
            if (!VALUE || !WHERE) {
                throw new Error(block.id)
            };
            return `${VALUE}.charAt(${WHERE})`;
        }

        javascriptGenerator.forBlock['text_includes'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const WHERE = getValue(block, generator, 'WHERE')
            if (!VALUE || !WHERE) {
                throw new Error(block.id)
            };
            return `${VALUE}.includes(${WHERE})`;
        }

        javascriptGenerator.forBlock['text_replace'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const WHERE = getValue(block, generator, 'WHERE')
            const VAR = getValue(block, generator, 'VAR') || ''
            if (!VALUE || !WHERE) {
                throw new Error(block.id)
            };
            return `${VALUE}.replace(${WHERE},${VAR})`;
        }

        javascriptGenerator.forBlock['text_split'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const WHERE = getValue(block, generator, 'WHERE')
            if (!VALUE || !WHERE) {
                throw new Error(block.id)
            };
            return `${VALUE}.split(${WHERE})`;
        }

        javascriptGenerator.forBlock['text_substring'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const START = getValue(block, generator, 'START')
            const END = getValue(block, generator, 'END') || ''
            if (!VALUE || !START || !END) {
                throw new Error(block.id)
            };
            return `${VALUE}.substring(${START},${END})`;
        }

        javascriptGenerator.forBlock['text_code_from'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            if (!VALUE) {
                throw new Error(block.id)
            };
            return `String.fromCharCode(${VALUE})`;
        }

        javascriptGenerator.forBlock['text_code_to'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const INDEX = getValue(block, generator, 'INDEX')
            if (!VALUE || !INDEX) {
                throw new Error(block.id)
            };
            return `${VALUE}.charCodeAt(${INDEX})`;
        }

        javascriptGenerator.forBlock['text_encoder'] = function () {
            return `(new TextEncoder())`;
        }

        javascriptGenerator.forBlock['text_encoder_encode'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const TARGET = getValue(block, generator, 'TARGET')
            if (!VALUE || !TARGET) {
                throw new Error(block.id)
            };
            return `${TARGET}.encode(${VALUE})`;
        }

        javascriptGenerator.forBlock['text_decoder'] = function () {
            return `(new TextDecoder())`;
        }

        javascriptGenerator.forBlock['text_decoder_decode'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const TARGET = getValue(block, generator, 'TARGET')
            if (!VALUE || !TARGET) {
                throw new Error(block.id)
            };
            return `${TARGET}.decode(${VALUE})`;
        }
    }
}
